import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Tabs,Card,Pagination,Row,Col } from 'antd';
import {toJS} from "mobx";
import {Condition,getAdButtons} from './list/listCondition';
import {WeaTableNew} from 'comsMobx';
import ModifyLogDialog from "./dialog/modifyLogDialog"
import ExchangeDialog from './dialog/exchangeDialog'

const WeaTable = WeaTableNew.WeaTable;
import {WeaRightMenu,WeaTop,WeaTab,WeaErrorPage,WeaBrowser,WeaTools,WeaProgress,WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

@inject('prjApprovalStore')
@observer
class Approval extends React.Component {
    constructor(props) {
        super(props);
        window._cptTable = {
            reLoad: props.prjApprovalStore.reLoad
        }
	}

    componentDidMount() {
        this.doInit(this.props);
    }
    doInit(props){
        const { location,prjApprovalStore } = props;
        const {initDatas,doSearch,initTreeDatas} = prjApprovalStore;
        initDatas();
        doSearch();
    }

    componentWillReceiveProps(nextProps){
        if(this.props.location.key !== nextProps.location.key){
            const { location,prjApprovalStore } = nextProps;
            prjApprovalStore.clearStatus();
            this.doInit(nextProps);
        }
    }

    componentWillUnmount(){
        const { prjApprovalStore } = this.props;
        prjApprovalStore.clearStatus();
    }
    render(){
        const {prjApprovalStore} = this.props;
        const {loading,tableStore,showSearchAd,form,exchangeStore,logTableStore,logVisible} = prjApprovalStore;
        const formParams = form.getFormParams() || {};
        return (
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@gnbydh`} datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}  >
            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@zutvpq`}
                title={getLabel(16410,"审批任务")}
                loading={loading}
                icon={<i className='icon-coms-project' />}
                iconBgcolor='#217346'
                buttons={this.getTopButtons()}
                buttonSpace={10}
                showDropIcon={true}
                dropMenuDatas={this.getRightMenu()}
                onDropMenuClick={this.onRightMenuClick.bind(this)} 
            >
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@f8b4as`}
                    buttonsAd={getAdButtons(prjApprovalStore,this.props.ecId || '')}
                    searchType={['base','advanced']}
                    searchsBaseValue={formParams.taskname}
                    setShowSearchAd={bool=>{prjApprovalStore.setShowSearchAd(bool)}}
                    hideSearchAd={()=> prjApprovalStore.setShowSearchAd(false)}
                    searchsAd={
                        <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@juuuhw`} listStore={prjApprovalStore} form={form} onEnterSearch={this.onEnterSearch} ></Condition></div>
                    }
                    showSearchAd={showSearchAd}
                    onSearch={v=>{prjApprovalStore.doSearch()}}
                    onSearchChange={v=>{prjApprovalStore.appendFormFields({taskname:{value:v}})}}
                />
                    <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@crkoxg`} 
                        comsWeaTableStore={tableStore}
                        hasOrder={true}
                        needScroll={true}
                        getColumns={c=>this.reRenderColumns(c)}
                        tableWidth={this.tableWidth}
                        onOperatesClick={this.onOperatesClick.bind(this)}
                    />
            </WeaTop>
            <ExchangeDialog ecId={`${this && this.props && this.props.ecId || ''}_ExchangeDialog@do9fwa`} contentStore={exchangeStore}  />
            <ModifyLogDialog ecId={`${this && this.props && this.props.ecId || ''}_ModifyLogDialog@zbi505`} ref="modifyLogDialog" title={getLabel(83905,"任务修改记录")}  tableStore={logTableStore}/>
        </WeaRightMenu>)

    }
    getTopButtons(){
        const {prjApprovalStore} = this.props;
        const {rightMenu,tableStore} = prjApprovalStore;
        let {selectedRowKeys} = tableStore;
       let btnArr = [];
       let that = this;
       const isDisabled = !(selectedRowKeys.length>0 && `${toJS(selectedRowKeys)}`);
       rightMenu && rightMenu.length>0 && toJS(rightMenu).map(m=>{
           m.isTop == '1' && btnArr.length < 4 && btnArr.push(
               <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9onnbz@${m.type}`} type="primary" 
                   disabled={isDisabled && m.isControl == "1"}
                   onClick={()=>{
                        if(m.type == "BTN_BATCHAPPROVE"){
                            prjApprovalStore.doTaskApprovalOpt({method:'approve',taskids:`${toJS(selectedRowKeys)}`});
                        }else if(m.type == "BTN_BATCHBACK"){
                            prjApprovalStore.doTaskApprovalOpt({method:"refuse",taskids:`${toJS(selectedRowKeys)}`});
                        }
                   }}>
                   {m.menuName}
               </Button>
           );
       });
       return btnArr;
    }

    getRightMenu(){
        const {prjApprovalStore }= this.props;
        const {rightMenu,tableStore} = prjApprovalStore;
        let {selectedRowKeys} = tableStore;
        let btnArr = [];
        const isDisabled = !(selectedRowKeys.length>0 && `${toJS(selectedRowKeys)}`);
        rightMenu && rightMenu.length>0 && rightMenu.map(m=>{
            btnArr.push({
                icon: <i className={m.menuIcon} />,
                content: m.menuName,
                disabled:isDisabled && m.isControl == "1"
            })
        });
    	return btnArr
    }
    onRightMenuClick(key){
        const {prjApprovalStore }= this.props;
        const {rightMenu,tableStore} = prjApprovalStore;
        let {selectedRowKeys} = tableStore;
        let that = this;
        rightMenu &&  rightMenu.length>0  && rightMenu.map((m,i)=>{
        	if(Number(key) == i){
                let fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
                if(m.type == "BTN_COLUMN"){ //定制列
                    prjApprovalStore.onShowColumn();
                }else if(m.type == "BTN_BATCHAPPROVE"){
                    prjApprovalStore.doTaskApprovalOpt({method:'approve',taskids:`${toJS(selectedRowKeys)}`});
                }else if(m.type == "BTN_BATCHBACK"){
                    prjApprovalStore.doTaskApprovalOpt({method:"refuse",taskids:`${toJS(selectedRowKeys)}`});
                }
            }
        });
    }

    reRenderColumns(columns){
        columns.forEach((c,i)=>{
            if(c.dataIndex=='finish'){
                c.render = function(text, record){
                    return  <span  className='wea-prj-progressStyle' >
                    <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@qol3mq@${i}`} percent={record.finish||0}  strokeColor={record.finishspan} />
                </span>
                }
            } else {
              c.render = function(text, record){
                  let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
                  return <span dangerouslySetInnerHTML={{__html: valueSpan}}></span>
                }
            }
        })
        return columns;
    }

    tableWidth = (columns) => {
        let width = 0;
        let cols = 0;
        columns.map(col => {
          if (col.display === 'true') {
            let oldwidth = col.oldWidth || '10%';
            let widthInt = parseFloat(oldwidth.replace('%', ''));
            if (widthInt <= 0) {
              widthInt = 10;
            }
            width += widthInt;
            cols++
          }
        })
        //超过10列，才出现滚动条，width>100才出现滚动条
        if(cols<=10){
            width = 100 ;
        }
        return `${width}%`;
    }

    onOperatesClick(record,index,operate,flag){
        let that = this;
        const {prjApprovalStore }= this.props;
        const {doTaskApprovalOpt,viewModifyLog,exchangeStore} = prjApprovalStore;

        let _href = operate && operate.href ? operate.href : "";
        let fn = _href.replace("javascript:","");
		fn = fn.substring(0,fn.indexOf('('));
        if(fn != ""){
           if("onApprove"==fn){
                doTaskApprovalOpt({method:'approve',taskids:record.randomFieldId});
           }else if('onReject' == fn){
                doTaskApprovalOpt({method:"refuse",taskids:record.randomFieldId});
           }else if('onLog' == fn){
                viewModifyLog(record.randomFieldId);
                this.refs.modifyLogDialog.setVisible(true);
            }else if('onDiscuss' == fn){   //相关交流
                exchangeStore.handleExchangeDialog(true,"task",record.randomFieldId,{})
            }
       }
   }
    onEnterSearch = () =>{
        const {prjApprovalStore} = this.props;
        prjApprovalStore.doSearch();
        prjApprovalStore.setShowSearchAd(false);
    }
}

export default WeaTools.tryCatch(React,
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@p2sgak`} msg={ props.error ? props.error : getLabel(383324,"对不起，该页面异常，请联系管理员")} />,
    {error: ""}
)(Approval);